package net.xdclass.controller;

import com.fasterxml.jackson.databind.ser.std.StdKeySerializers;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.service.NotifyService;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import org.apiguardian.api.API;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author NJUPT wly
 * @Date 2021/9/13 1:49 下午
 * @Version 1.0
 */
@Api(tags = "通知模块")
@RestController
@RequestMapping("/api/user/v1")
@Slf4j
public class NotifyController {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private NotifyService notifyService;


    //单位毫秒
    private static final long CAPTURE_CODE_EXPIRE = 60*1000*10;

    /**
     * 获取图形验证码
     * @param request
     * @param response
     */
    @ApiOperation("获取图形验证码")
    @RequestMapping("captcha")
    public void getCapture(HttpServletRequest request, HttpServletResponse response){
        String capture = captchaProducer.createText();
        log.info("图形验证码:{}",capture);

        //存储
        stringRedisTemplate.opsForValue().set(getCaptchaKey(request),capture,CAPTURE_CODE_EXPIRE, TimeUnit.MILLISECONDS);

        BufferedImage image = captchaProducer.createImage(capture);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.info("获取图形验证码异常:{}",e);
        }
    }

    /**
     * 发送邮箱验证码
     * @param to
     * @param captcha
     * @param request
     * @return
     */
    @ApiOperation("发送邮箱验证码")
    @GetMapping("send_code")
    public JsonData sendRegisterCode(@RequestParam(value = "to",required = true)String to,
                                     @RequestParam(value = "captcha",required = true)String captcha,
                                     HttpServletRequest request){
        String key = getCaptchaKey(request);
        String cacheKey = stringRedisTemplate.opsForValue().get(key);
        if (captcha != null && captcha.equalsIgnoreCase(cacheKey)){
            //成功
            stringRedisTemplate.delete(key);
            return notifyService.sendCode(SendCodeEnum.USER_REGISTER,to);
        } else {
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }
    }

    private String getCaptchaKey(HttpServletRequest request){
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");

        String key = "user-service:captcha:" + CommonUtil.MD5(ip + userAgent);
        log.info("ip={}",ip);
        log.info("userAgent={}",userAgent);
        log.info("key={}",key);
        return key;
    }



}
